<template>
  <div class="container">
    <div id="cesiumContainer" ref="earthContainer"></div>
    <div class="measure">
      <ul>
        <li v-on:click="submergence(3.0)">淹没3m</li>
        <li v-on:click="submergence(4.0)">淹没4m</li>
      </ul>
    </div>
  </div>
</template>

<script>
import DrawPoint from "./DrawPoint";
export default {
  name: "Home",
  data() {
    return {
      _earth: null,
      drawPolygonTool: undefined,
      drawPointTool: undefined,
      waterPrimitive: undefined
    };
  },
  components: {
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 1.1.1 创建地球
      // eslint-disable-next-line no-undef
      var earth = new XE.Earth(this.$refs.earthContainer, {
        selectionIndicator: true,
        infoBox: false
      });
      // eslint-disable-next-line no-undef
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlYWI2ZTA4Yy04NGM3LTQxODItOGFiYS1kNmZiNGYyNDY0NzQiLCJpZCI6Mzk2MSwic2NvcGVzIjpbImFzciIsImdjIl0sImlhdCI6MTUzOTQwNzAzMX0.okbBR7vmM5YvSjAxKTAqvLjsG5eELUJYacmrpMUkx3Q";
      this._earth = earth;
      window.earth = earth;
      this.controlImagerLayer(
        "http://t1.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=919e3ee2639d547b659a42a441d33ad7"
      );
      this.controlImagerLayer(
        "http://t1.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=919e3ee2639d547b659a42a441d33ad7"
      );
      this.controlTile(
        "http://chonglin.giseden.xyz:2217/qdyjgl/mx/tileset.json",{
                                        ref: 'http://chonglin.giseden.xyz:2217/qdyjgl/mx/tileset.json',
                                        czmObject: {
                                            xbsjType: "Tileset",
                                            xbsjGuid: "2f3c8d84-d4dd-489d-b2c1-78ab4f8ad855",
                                            name: "未命名瓦片",
                                            url: "http://chonglin.giseden.xyz:2217/qdyjgl/mx/tileset.json",
                                            xbsjPosition: [
                                                2.0314101824408635,
                                                0.6965069770812539,
                                                0.0
                                            ],
                                            xbsjUseOriginTransform: false,
                                            xbsjClippingPlanes: {},
                                            xbsjCustomShader: {}
                                        }
                                    }
      );
    //   this.addGlobalTerrian()
      this.drawPointTool = new DrawPoint({
        Cesium: Cesium,
        callback: "callback",
      });
      this.drawPointTool.setViewer(earth);
    //   this.drawPointTool.startCreate();
    //   this._earth._viewer.entities.add({
    //     id: 'yanmoid',
    //     name: '淹没',
    //     polygon: {
    //       hierarchy: Cesium.Cartesian3.fromDegreesArray([116.3900698682,39.9080545399,116.3901742466,39.9058228965,116.3923488001,39.9058236385,116.3923772442,39.9080606414]),
    //       extrudedHeight: 4,
    //       material: new Cesium.ColorMaterialProperty(Cesium.Color.LIGHTSKYBLUE.withAlpha(0.7)),
    //     }
    //   })
    },

    submergence(val){
        if(this.waterPrimitive){
            this._earth._viewer.scene.primitives.remove(this.waterPrimitive)
        }
        this.waterPrimitive = new Cesium.Primitive({
            show:true,// 默认隐藏
            allowPicking:false,
            geometryInstances : new Cesium.GeometryInstance({
                geometry : new Cesium.PolygonGeometry({
                    polygonHierarchy : new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray([116.3900698682,39.9080545399,116.3901742466,39.9058228965,116.3923488001,39.9058236385,116.3923772442,39.9080606414])),
                    height:val 
                    // extrudedHeight: 10,//注释掉此属性可以只显示水面
                    // perPositionHeight : true//注释掉此属性水面就贴地了
                })
            }),
            // 可以设置内置的水面shader
            appearance : new Cesium.EllipsoidSurfaceAppearance({
                material : new Cesium.Material({
                    fabric : {
                        type : 'Water',
                        uniforms : {
                            //baseWaterColor:new Cesium.Color(0.0, 0.0, 1.0, 0.5),
                            //blendColor: new Cesium.Color(0.0, 0.0, 1.0, 0.5),
                            //specularMap: 'gray.jpg',
                            normalMap: require('../assets/12.jpg'),
                            frequency: 1000.0,
                            animationSpeed: 0.01,
                            amplitude: 10.0
                        }
                    }
                })
            })
        });
        this._earth._viewer.scene.primitives.add(this.waterPrimitive);
    },


    // #region 影像图层控制
    controlImagerLayer(url) {
      const imager = arguments[1];
      if (
        this.containsKey(this._earth.sceneTree.$refs, url) &&
        this._earth.sceneTree.$refs[url].czmObject._imageryLayer
          ._imageryProvider.url !== ""
      ) {
        this.deleteImagerLayer(url);
      } else {
        this.addImagerLayer(url, imager);
      }
    },
    addImagerLayer(url) {
      const imager = arguments[1];
      let imagerObj;
      if (typeof imager === "undefined") {
        imagerObj = {
          ref: url,
          czmObject: {
            name: url,
            xbsjType: "Imagery",
            xbsjImageryProvider: {
              XbsjImageryProvider: {
                url: url,
                srcCoordType: "WGS84",
                dstCoordType: "WGS84"
              }
            }
          }
        };
      } else {
        imagerObj = imager;
      }

      if (this._earth.sceneTree.$refs[url]) {
        this._earth.sceneTree.$refs[url].czmObject = imagerObj.czmObject;
      } else {
        this._earth.sceneTree.root.children.push(imagerObj);
      }
    },
    deleteImagerLayer(url) {
      this._earth.sceneTree.$refs[url].czmObject = {};
    },
    containsKey(obj, key) {
      let result = false;
      for (const k in obj) {
        if (k === key) {
          result = true;
          break;
        }
      }
      return result;
    },
    // #endregion

    // #region 地形数据控制
    controlTerrain(url) {
      if (
        this.containsKey(this._earth.sceneTree.$refs, url) &&
        this._earth.sceneTree.$refs[url].czmObject._terrainProvider._layers[0]
          .resource._url !== ""
      ) {
        this.removeTerrain(url);
      } else {
        this.addTerrain(url);
      }
    },
    addTerrain(url) {
      const terrain = {
        ref: url,
        czmObject: {
          xbsjType: "Terrain",
          name: url,
          xbsjTerrainProvider: {
            type: "XbsjCesiumTerrainProvider",
            XbsjCesiumTerrainProvider: {
              url: url,
              requestVertexNormals: true,
              requestWaterMask: true
            }
          }
        }
      };
      if (this._earth.sceneTree.$refs[url]) {
        this._earth.sceneTree.$refs[url].czmObject = terrain.czmObject;
      } else {
        this._earth.sceneTree.root.children.push(terrain);
      }
    },
    removeTerrain(url) {
      this._earth.sceneTree.$refs[url].czmObject = {};
    },
    addGlobalTerrian() {
      // eslint-disable-next-line
      this._earth._viewer.terrainProvider = new Cesium.createWorldTerrain({
        // eslint-disable-next-line
        url: Cesium.IonResource.fromAssetId(1),
        requestWaterMask: true,
        requestVertexNormals: true
      });
    },
    removeGlobalTerrian() {
      // eslint-disable-next-line
      this._earth._viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider();
    },
    // #endregion

    // #region 模型图层控制
    controlTile(url) {
      const tileJson = arguments[1];
      if (
        this.containsKey(this._earth.sceneTree.$refs, url) &&
        this._earth.sceneTree.$refs[url].czmObject.url !== ""
      ) {
        this.unloadTile(url);
      } else {
        this.loadTile(url, tileJson);
      }
    },
    sceneTreeRemoveItem(fucText) {
      this._earth.sceneTree.root.children.forEach(element => {
        if (element.czmObject.name === fucText) {
          element.czmObject = {};
        }
      });
    },
    loadTile(url) {
      console.log(url);
      const tileJson = arguments[1];
      let tile;
      if (tileJson) {
        tile = tileJson;
      } else {
        tile = {
          ref: url,
          czmObject: {
            xbsjType: "Tileset",
            name: url,
            url: url
          }
        };
      }
      if (this._earth.sceneTree.$refs[url]) {
        this._earth.sceneTree.$refs[url].czmObject = tile.czmObject;
      } else {
        this._earth.sceneTree.root.children.push(tile);
      }
      this._earth.sceneTree.$refs[url].czmObject.maximumScreenSpaceError = 1.0;
      this._earth.sceneTree.$refs[url].czmObject.flyTo();
    },
    unloadTile(url) {
      console.log("un" + url);
      this._earth.sceneTree.$refs[url].czmObject = {};
    }
    // #endregion
  }
};
</script>
<style scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.measure {
  position: absolute;
  top: 1px;
  background-color: #555758;
  padding: 5px;
  height: 30px;
  color: #fff;
}

ul {
  margin: 0;
  padding: 0;
}

ul li {
  list-style-type: none;
  float: left;
  cursor: pointer;
  margin: 0px 3px;
  border: 1px;
}
</style>
